using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using SMSManager.Commn.Interfaces;
using SMSManager.Commn.Interfaces.ViewModels;
using SMSManager.Data;

namespace SMSManager.WpfClient.ViewModels
{
	[Export(typeof (ISMSServiceViewModel))]
	[PartCreationPolicy(CreationPolicy.NonShared)]
	public class SMSServiceViewModel : NotifyPropertyChangedBase, ISMSServiceViewModel
	{
		private readonly CompositionContainer _container;

		private ISMSService _smsService;

		[ImportingConstructor]
		public SMSServiceViewModel(CompositionContainer container)
		{
			_container = container;
		}

		private void SetName()
		{
			if (_smsService.IsLogin)
			{
				int smsCount = _smsService.GetSMSCount();
				if (smsCount >= 0)
				{
					Name = string.Format("{0}({1})", _smsService.Name, smsCount);
					this.OnPropertyChanged(x => x.Name);
					return;
				}
			}
			Name = _smsService.Name;
			this.OnPropertyChanged(x => x.Name);
		}

		private void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "IsLogin" || e.PropertyName == "ResultMessage")
			{
				SetName();
			}
		}

		public ISMSService SMSService
		{
			set
			{
				_smsService = value;

				Name = _smsService.Name;
			}
		}

		public IUser User
		{
			set
			{
				if (_container == null) throw new NullReferenceException();
				var loginViewModel = _container.GetExportedValue<ILoginViewModel>();

				if (_smsService == null) throw new NullReferenceException();
				loginViewModel.SMSService = _smsService;

				loginViewModel.User = value;

				LoginViewModel = loginViewModel;

				LoginViewModel.PropertyChanged += ViewModelPropertyChanged;

				if (value.IsAutoLogin)
				{
					_smsService.Login(value);
					SetName();
				}
			}
		}

		public ISMSInfo SMSInfo
		{
			set
			{
				if (_container == null) throw new NullReferenceException();
				var smsSendViewModel = _container.GetExportedValue<ISMSSendViewModel>();

				if (_smsService == null) throw new NullReferenceException();
				smsSendViewModel.SMSService = _smsService;

				smsSendViewModel.SMSInfo = value;

				SMSSendViewModel = smsSendViewModel;

				SMSSendViewModel.PropertyChanged += ViewModelPropertyChanged;
			}
		}


		public ILoginViewModel LoginViewModel { get; private set; }

		public ISMSSendViewModel SMSSendViewModel { get; private set; }

		public string Name { get; private set; }

		public string SMSServiceName
		{
			get { return _smsService.Name; }
		}
	}
}